package com.itheima.train.common.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSON;
import com.itheima.train.common.core.JsonResult;
import com.itheima.train.common.util.RequestHolder;
import com.itheima.train.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Liang
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public JsonResult<Object> handleException(Throwable e) {
        log.error("异常处理", e);
        return buildResponseEntity(ExceptionUtil.getRootCauseMessage(e));
    }

    /**
     * 统一返回
     */
    private JsonResult<Object> buildResponseEntity(String errMsg) {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        String uri = request.getRequestURI();
        String method = request.getMethod();
        String contentType = request.getContentType();
        String ip = StringUtils.getIp(request);
        Map<String, String[]> params = request.getParameterMap();
        //String username = SecurityUtils.getLogUsername();
        //[username:%s]-
        log.error(String.format("异常信息：[ip:%s]-[params:%s]-[contentType:%s]-[method:%s]-[uri:%s]-[message:%s]",
                //username,
                ip, JSON.toJSONString(params), contentType, method, uri, errMsg));
        return JsonResult.buildError(errMsg);
    }
}
